import { cls, type StyledProps, setCSS, unsafe } from '@knno/jsx';
import { iconStyle } from './icon.css';

export type IconProps = StyledProps<SVGElement> & {
	svg: string;
	size?: string;
	color?: string;
	onClick?: (this: SVGElement, e: MouseEvent) => void;
	onPointerDown?: (this: SVGElement, e: PointerEvent) => void;
	onPointerUp?: (this: SVGElement, e: PointerEvent) => void;
};

export function Icon(props: IconProps) {
	const svg = unsafe(props.svg).firstElementChild as SVGElement;
	svg.classList.add(...cls(props.class, iconStyle));
	if (props.size) {
		svg.style.width = props.size;
	}
	if (props.size) {
		svg.style.height = props.size;
	}
	if (props.color) {
		svg.style.fill = props.color;
	}
	setCSS(svg, props.style ?? {});
	if (props.onClick) {
		svg.addEventListener('click', props.onClick);
	}
	if (props.onPointerDown) {
		svg.addEventListener('pointerdown', props.onPointerDown);
	}
	if (props.onPointerUp) {
		svg.addEventListener('pointerup', props.onPointerUp);
	}
	props.ref?.(svg);
	return svg;
}
